// 添加新用户
const cloud = require('wx-server-sdk')

cloud.init({
  env: cloud.DYNAMIC_CURRENT_ENV
})

const db = cloud.database()

exports.main = async (event, context) => {
  try {
    const { nickname, level, score } = event
    
    // 验证参数
    if (!nickname || !level || score === undefined) {
      return {
        success: false,
        error: '参数不完整'
      }
    }
    
    // 检查用户名是否已存在
    const existUser = await db.collection('users')
      .where({ nickname })
      .get()
    
    if (existUser.data.length > 0) {
      return {
        success: false,
        error: '用户昵称已存在'
      }
    }
    
    // 添加用户
    const result = await db.collection('users').add({
      data: {
        nickname,
        level,
        score: parseInt(score),
        avatar: '/static/images/default-avatar.png',
        createTime: new Date(),
        updateTime: new Date()
      }
    })
    
    return {
      success: true,
      data: result
    }
  } catch (error) {
    console.error('添加用户失败:', error)
    return {
      success: false,
      error: error.message
    }
  }
}
